﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Text;

using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;

namespace WebSite.admin.order
{
    public partial class orderQuery : BaseAdmin
    {
        DALCardType theCardType = new DALCardType();
        DALOrder theOrder = new DALOrder();
        dalCompany theCompany = new dalCompany();


        void BindCardType()
        {
            DataSet dsCardType = theCardType.GetList("1=1");
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = dsCardType;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
            this.ddlCardType.SelectedValue = "-1";

        }


        protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            DataTable table = theOrder.GetListByPage(GetSql(), string.Format("{0} {1}", e.SortField, e.SortDirection), Grid1.PageIndex, Grid1.PageSize).Tables[0];
            Grid1.DataSource = table;
            Grid1.DataBind();
            ViewState["sort"] = e.SortField;
            ViewState["dir"] = e.SortDirection;
        }


        void BindPublishCompanyList()
        {
            DataSet dsPublishCompany = theCompany.GetList(" LevelId = 1");
            this.ddlPublishCompany.DataSource = dsPublishCompany;
            this.ddlPublishCompany.DataTextField = "name";
            this.ddlPublishCompany.DataValueField = "id";
            this.ddlPublishCompany.DataBind();

            if (base.CompanyLevelId == "1")
            {
                this.ddlPublishCompany.Items.FindByValue(base.CompanyId).Selected = true;
                this.ddlPublishCompany.Enabled = false;
            }
            this.ddlPublishCompany.Items.Insert(0, new ExtAspNet.ListItem("所有", "-1"));
            this.ddlPublishCompany.SelectedValue = "-1";
        }

        protected void Grid1_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            GridViewBind();
        }

        private string GetSql()
        {
            string sql = " 1=1 ";
            if (this.txtOrderCode.Text.Trim() != "")
            {
                sql = sql + " and T.ordercode like '%" + this.txtOrderCode.Text.Trim() + "%'";
            }
            if (this.txtGoodsName.Text.Trim() != "")
            {
                sql = sql + " and T.orderid in(select orderid from DB_Car c join tbGoods s on c.productid = s.goodsId  where s.goodsName like '%" + this.txtGoodsName.Text.Trim() + "%') ";
            }
            if (this.ddlOrderStates.SelectedItem.Value != "-1")
            {
                sql = sql + " and T.states=" + this.ddlOrderStates.SelectedItem.Value;
            }

            if (this.dpSendDateFrom.Text.Trim() != "")
            {
                sql = sql + " and (T.sendDate >= '" + this.dpSendDateFrom.Text.Trim() + "' or T.sendDate is null)";
            }
            if (this.dpSendDateTo.Text.Trim() != "")
            {
                sql = sql + " and (T.sendDate <= '" + this.dpSendDateTo.Text.Trim() + " 23:59' or T.sendDate is null)";
            }

            if (this.ddlPublishCompany.SelectedItem.Value != "-1")
            {
                sql = sql + " and T.OrderCode in (select oa.orderCode from tbOrderAccount oa join DB_Card c on oa.cardId = c.CardId and c.CompanyId = " + this.ddlPublishCompany.SelectedItem.Value + ")";
            }
            //--
            if (this.ddlCardType.SelectedItem.Value != "-1")
            {
                sql = sql + " and T.OrderCode in (select oa.orderCode from tbOrderAccount oa join DB_Card c on oa.cardId = c.CardId and  c.CardTypeId = " + this.ddlCardType.SelectedItem.Value + ")";
            }


            if (this.txtAddress.Text.ToString() == "")
            {
                sql = sql + " and T.address1 like '%" + this.txtAddress.Text.ToString().Trim() + "%' ";
            }

            if (this.txtCname.Text.ToString() != "")
            {
                sql = sql + " and T.cname1 like '%" + this.txtCname.Text.ToString().Trim() + "%' ";
            }

            if (this.txtLinkWay.Text.ToString() != "")
            {
                sql = sql + " and (T.tel1 like '%" + this.txtLinkWay.Text.ToString().Trim() + "%' or T.phone1 like '%" + this.txtLinkWay.Text.ToString().Trim() + "%')";
            }
            if (Request.QueryString["type"] == "me")
            {
                sql = sql + " and cname='" + base.AdminUser + "' ";
            }

            return sql;
        }

        private void GridViewBind()
        {

            string sSql = GetSql();
            Grid1.RecordCount = theOrder.GetRecordCount(sSql);
            string strOrderBy = string.Format("{0} {1} "
                                               , ViewState["sort"] == null ? null : ViewState["sort"].ToString()
                                               , ViewState["dir"] == null ? null : ViewState["dir"].ToString());
            if (strOrderBy.Length < 13)
            {
                strOrderBy = "orderTime desc ";
            }
            DataTable table = theOrder.GetListByPage(sSql, strOrderBy, Grid1.PageIndex, Grid1.PageSize).Tables[0];
            Grid1.DataSource = table;
            Grid1.DataBind();
            Grid1.SelectedRowIndexArray = new int[] { };
        }

        private DataTable GetExportData()
        {
            string sql = "select distinct '' as 物流公司, '' as 物流单号,'' as 物流查询网址,'' as 物流查询电话,'' as 发货时间,订单号 as 寄件客户编码_订单编号,'团购部' as 寄件人,'' as 寄件公司,isnull(供货商,'') as 供货商, "
                         + " '' as 寄件人联系电话,'' as 寄件人地址,商品名称,"
                         + " sum(goodsCount) as 数量,收货人,'' as 收货公司,收货人联系电话,收货地址, 备注,'' as 付款方式,'' as 保价,'\\' as 保价金额,"
                         + "'' as 代收货款,'\\' as 代收货款卡号, '' as 代收货款金额,'' as 备注1,'' as 备注2, '' as 备注3 "
                         + " from  "
                         + " ( "
                         + " select T.ordercode as 订单号,"
                         + " S.goodsName+'(' + convert(varchar(30),C.goodsPoints) +')' as 商品名称,  T.cname1 as 收货人,isnull(T.tel1,'') + ';' + isnull(T.phone1,'') as 收货人联系电话,(select [name] from tbCompany where id=S.companyId) as 供货商,  convert(varchar(10),T.senddate,111) as 送货日期, T.address1 as 收货地址,T.SendCompany as 物流,T.SendCode as 物流单号,T.[content] as 备注 ,C.goodsCount "
                         + " from DB_order T join DB_Car C on T.orderCode = C.orderCode join tbGoods S on C.goodsId = S.goodsid "
                         + " where 1=1 and ";
            sql = sql + GetSql()
                  + " ) a "
                  + " group by 订单号,收货人, 收货人联系电话,收货地址,商品名称 ,备注,供货商 ";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }



        protected void Page_Load(object sender, EventArgs e)
        {

            if (!base.IsPostBack)
            {
                base.ValidateLoginRule(ERule.OrderQuerySelf);


                this.BindCardType();
                this.BindPublishCompanyList();

                this.GridViewBind();
            }
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称   
            DataTable dt = GetExportData();
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);

        }

        private string BuildExportHTML(System.Data.DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 5000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }







        private DataTable GetExportDataForTemplate()
        {
            string sql = "select top 0 '' as 订单号, "
                         + " '' as 送货日期,"
                         + " '' as 收件人,"
                         + " '' as 联系电话,"
                         + "'' as 送货地址,"
                         + " '' as 产品名称,"
                         + " '' as 数量,"
                         + " '' as 备注,"
                         + "'' as 物流,'' as 物流单号"
                         + " from DB_order O join DB_Car C on O.orderCode = C.orderCode join tbGoods S on C.goodsId = S.goodsId";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            return table;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.GridViewBind();
        }

        protected void btnInputOrder_Click(object sender, EventArgs e)
        {

        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            DataTable dt = GetExportData();
            Session["orderFile"] = dt;
            ExtAspNet.Alert.Show("导出卡券", "", "window.open('/admin/order/exportOrderList.aspx','_blank');");
        }




    }
}